"use client"

import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'
import { useToast } from '@/components/ui/use-toast'

export default function SetupPage() {
  const [username, setUsername] = useState('admin')
  const [password, setPassword] = useState('admin123')
  const [setupKey, setSetupKey] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [result, setResult] = useState<{success?: boolean, message?: string}>({})
  const { toast } = useToast()

  const handleSetup = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!username || !password || !setupKey) {
      toast({
        variant: "destructive",
        title: "表单不完整",
        description: "请填写所有字段"
      })
      return
    }

    setIsLoading(true)
    try {
      const response = await fetch('/api/admin/setup', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          username,
          password,
          key: setupKey
        })
      })

      const data = await response.json()
      
      if (response.ok) {
        setResult({
          success: true,
          message: data.message || '管理员创建成功'
        })
        toast({
          title: "成功",
          description: data.message || '管理员创建成功'
        })
      } else {
        setResult({
          success: false,
          message: data.message || '创建失败'
        })
        toast({
          variant: "destructive",
          title: "错误",
          description: data.message || '创建管理员失败'
        })
      }
    } catch (error) {
      console.error('设置错误:', error)
      setResult({
        success: false,
        message: '发生未知错误，请检查控制台'
      })
      toast({
        variant: "destructive",
        title: "错误",
        description: '发生未知错误，请检查控制台'
      })
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-[#0c0f14] p-4">
      <Card className="w-full max-w-md border-gray-800 bg-[#1a1d24] text-white">
        <CardHeader>
          <CardTitle>创建管理员账号</CardTitle>
          <CardDescription>使用安全密钥设置初始管理员</CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSetup} className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="username">用户名</Label>
              <Input
                id="username"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                className="bg-[#252a33] border-gray-700"
                disabled={isLoading}
              />
            </div>
            
            <div className="space-y-2">
              <Label htmlFor="password">密码</Label>
              <Input
                id="password"
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className="bg-[#252a33] border-gray-700"
                disabled={isLoading}
              />
            </div>
            
            <div className="space-y-2">
              <Label htmlFor="setupKey">安全密钥 (ADMIN_SETUP_KEY)</Label>
              <Input
                id="setupKey"
                type="password"
                value={setupKey}
                onChange={(e) => setSetupKey(e.target.value)}
                className="bg-[#252a33] border-gray-700"
                disabled={isLoading}
                placeholder="输入.env文件中的ADMIN_SETUP_KEY值"
              />
              <p className="text-xs text-gray-400">在.env文件中查找ADMIN_SETUP_KEY的值</p>
            </div>
            
            <Button 
              type="submit" 
              className="w-full bg-blue-600 hover:bg-blue-700"
              disabled={isLoading}
            >
              {isLoading ? '处理中...' : '创建管理员'}
            </Button>
          </form>
          
          {result.message && (
            <div className={`mt-4 p-3 rounded ${result.success ? 'bg-green-900/50 text-green-200' : 'bg-red-900/50 text-red-200'}`}>
              {result.message}
            </div>
          )}
        </CardContent>
        <CardFooter className="flex flex-col space-y-2">
          <p className="text-xs text-gray-500">
            创建管理员后请务必移除或保护此页面
          </p>
          {result.success && (
            <Button 
              variant="outline" 
              className="w-full"
              onClick={() => window.location.href = '/admin'}
            >
              前往管理员登录
            </Button>
          )}
        </CardFooter>
      </Card>
    </div>
  )
} 